#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @ProjectName      : license
# @File             : license.py
# @Author           : LUCY
# @Product          : PyCharm
# @Time             : 2022/3/18 10:41

import base64
import win32api
import uuid
import wmi
import sys, os, time, datetime
from pyDes import des, PAD_PKCS5, ECB
import configparser
from django.conf import settings
from django.db import connection

qc64 = 'iVBORw0KGgoAAAANSUhEUgAAAjgAAANUCAYAAAC+NFdjAAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzsvXmcHGW1//95auu9JzOBkEwmKIEsJMpiQBJFkQCCQsTrJaBfDXpl8yKLLCpyVUTcFxZFFFwB9XchuCCCCyEiFyEsEVETsmBQk0zCksxkequu7fn9UV011T29VPUyvcx5vwgz011Vz3lq/dQ55zkPQBAEQRAE0WOwyWyMT3J7BEEQBEF0BwzgTd5ec6gmXv792mOnKSZfCi68FgwHceAQxnAAOJIAYmCQm2UHQRAEQRBdAIcBIA3gJc7xPBOwyWLmOkVnj++3+U/pSqv5FUJ1CZxanpjVWCkcu3jXSbDY2YLA3sw5H6y3LYIgCIIgphQawB4C43cb+4y7hnY8rlZbuJLg8S06qomaawF23FveIix4yXw34+xSMH4EAMnvtgmCIAiCIMqwlzH2bcNUb/jepidHAOCayoKGl/xdnXLC5trCZ4sA9oaFr5/GmPJZgbEPAIjWYz1BEARBEEQV9lqwrtkVUW/dtn69BQAbAV5O7DhCp6LAqSRsFgFsf7yFzVj8crif91/LwS4WQDk0BEEQBEG0Fgb8STXZqhc2C9sB4GU8zMsJHQbwsgKnVNx4hU1iSYrNyIaWSVxYzQQ2o3XdIAiCIAiCKIHhZRPmu/+af+lPM/r6rNT6BC8ndIqETDlhcxzeIgBAYkmKvbRvn3C4dMBnBEG4anJ6QRAEQRAEMYG8Cb5qa3bHfTlJ4uWEjitovOLG67F5efHLQjyfZzOsvvCscOQuAezk9vSFIAiCIAjCRdcs/p9/Hdv2UFxRLK/Q+SMetlip12Y1IDihqJf27RMihsGmYVp4RiS2VmDCke3qBUEQBEEQRBEM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2/l0PkQkgnsuuLT4EBVkcNLfraDTknOBeykbcDfVA6ltPsal0QRsiRB3bgZ/z7r3LLLtNtGoLoNlGQ8NSCBQ/QcToXe+MnH+84RIWz0nbuw89zLkN+4GZGlR9X0zESXHYX07/6A3Vd8GvmNmzHj01c21H7+uS146TNfDbzejM98FCGf4rTd5J/bgvzGzZBEEZFaM413KP3JJDK5nO0lFUVIhX/uMGyC6ABI4PQYvEF3qqbrLRsi7tCojdUYS6eh6TrkoUHM'

class register:
    def __init__(self):
        self.Des_Key = "BHC#@*UM"  # Key
        self.Des_IV = "\x22\x33\x35\x81\xBC\x38\x5A\xE7"  # 自定IV向量

    def getCVolumeSerialNumber(self):
        CVolumeSerialNumber = win32api.GetVolumeInformation("C:\\")[1]
        if CVolumeSerialNumber:
            return str(CVolumeSerialNumber)
        else:
            return 0

    def getDbSystemTime(self):
        with connection.cursor() as cursor:
            cursor.execute("select SYSDATE() from dual;")
            row = cursor.fetchone()
        return row[0]

    def getSystemTime(self):
        systime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if systime:
            return systime
        else:
            return 0

    def getValidTime(self):
        systime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()+180*24*60*60))
        if systime:
            return systime
        else:
            return 0

    def getSystemInfo(self):
        SystemInfo = win32api.GetSystemInfo()
        if SystemInfo:
            return str(SystemInfo)
        else:
            return 0

    def getHardDiskNumber(self):
        c = wmi.WMI()
        for physical_disk in c.Win32_DiskDrive():
            return physical_disk.SerialNumber.replace(' ', '')

    def get_mac_address(self):
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])

    # DES 加密
    def DesEncrypt(self, data):
        DES_SECRET_KEY = 'L&8C#U%Y'
        des_obj = des(DES_SECRET_KEY, ECB, DES_SECRET_KEY, padmode=PAD_PKCS5)
        secret_bytes = des_obj.encrypt((data).encode())
        if secret_bytes:
            secret_data = base64.b64encode(secret_bytes)
            return secret_data
        else:
            return 0

    def DesDecrypt(self, data):
        DES_SECRET_KEY = 'L&8C#U%Y'
        des_obj = des(DES_SECRET_KEY, ECB, DES_SECRET_KEY, padmode=PAD_PKCS5)
        secret_data = base64.b64decode(data)
        DecryptStr = des_obj.decrypt(secret_data).decode()
        return DecryptStr

    def EnSystemInfo(self):
        vol = str(input("请输入C盘卷号:"))
        mac = str(input("请输入MAC地址:"))
        valid_time = str(input("请输入授权时间:"))
        diskid = str(input("请输入磁盘序列号:"))
        time = reg.getSystemTime()
        # vol = reg.getCVolumeSerialNumber()
        # mac = reg.get_mac_address()
        #valid_time = reg.getValidTime()
        info = reg.getSystemInfo()
        # diskid = reg.getHardDiskNumber()

        data = mac + time + valid_time + diskid + vol + info + qc64
        secret_data = self.DesEncrypt(data)

        with open('license.dat', 'w') as f:
            f.write("[LICENSE]" + '\n')
            f.write("LicensedTime=" + time + '\n')
            f.write("CVol=" + vol + '\n')
            f.write("ValidTime=" + valid_time + '\n')
            f.write("DiskID=" + diskid + '\n')
            f.write("ServerMac=" + str(mac) + '\n')
            f.write("License=" + str(secret_data))
            f.close()
            print("授权License文件已生成，请替换到对应目录！")
            return "license.dat"

    def ParseLicense(self):
        config = configparser.ConfigParser()
        print(settings.BASE_DIR + '/license.dat')
        status = config.read(settings.BASE_DIR + '/license.dat')

        if len(status) == 0:
            return "License授权丢失，请联系管理员重新申请!"

        license = config.get('LICENSE', 'License')[2 : -1]
        data = self.DesDecrypt(license)
        mac = data[0 : 17]
        valid_time = datetime.datetime.strptime(data[36 : 55],'%Y-%m-%d %H:%M:%S')
        now_time = self.getDbSystemTime()
        isvalid = valid_time - now_time

        if mac != self.get_mac_address():
            return "非本服务器License，请联系管理员重新申请!"
        elif isvalid.days <= 0:
            return "License授权已过期，请联系管理员重新申请!"
        else:
            return True

    def getLicenseInfo(self):
        reg = register()
        mac = reg.getMacAddress()
        cvol = reg.getCVolumeSerialNumber()
        diskid = reg.getHardDiskNumber()
        systime = reg.getSystemTime()

        print("服务器授权License信息收集:")
        print("MAC地址    : " + mac)
        print("CVOL序列号 : " + cvol)
        print("磁盘ID     : " + diskid)
        print("系统时间   : " + systime)

if __name__ == '__main__':
    reg = register()
    license = reg.EnSystemInfo()

    # re = reg.ParseLicense()
    # print(re)


